<template>
  <el-dialog v-model="visible" :title="!dataForm.userId ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px">
      <el-form-item prop="username" :label="$t('user.username')" style="width: 400px;">
        <el-input v-model.trim="dataForm.username" :placeholder="$t('user.username')" :disabled="dataForm.userId"></el-input>
      </el-form-item>
      <!-- <el-form-item prop="realName" label="姓名">
        <el-input v-model="dataForm.remark" placeholder="姓名"></el-input>
      </el-form-item> -->
      <el-form-item prop="deptName" :label="$t('user.deptName')">
        <ren-dept-tree v-model="dataForm.deptId" :placeholder="$t('dept.title')" style="width: 280px !important;"
          v-model:deptName="dataForm.deptName"></ren-dept-tree>
      </el-form-item>
      <el-form-item prop="password" :label="$t('user.password')" :class="{ 'is-required': !dataForm.userId }"
        style="width: 400px;">
        <el-input v-model="dataForm.password"  :placeholder="$t('user.password')"></el-input>
      </el-form-item>
      <!-- <el-form-item prop="confirmPassword" :label="$t('user.confirmPassword')" style="width: 400px;"
        :class="{ 'is-required': !dataForm.userId }">
        <el-input v-model="dataForm.confirmPassword" type="password"
          :placeholder="$t('user.confirmPassword')"></el-input>
      </el-form-item> -->
      <el-form-item prop="remark" label="备注" style="width: 400px;">
        <el-input v-model.trim="dataForm.remark" placeholder="请输入备注"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" :label="$t('user.mobile')" style="width: 400px;">
        <el-input v-model="dataForm.mobile" :placeholder="$t('user.mobile')"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱" style="width: 400px;">
        <el-input v-model.trim="dataForm.email" placeholder="请输入邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item prop="roleIdList" :label="$t('user.roleIdList')" class="role-list">
        <el-checkbox-group v-model="dataForm.roleIdList" multiple :placeholder="$t('user.roleIdList')">
          <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId" :value="role.roleId">
            <span v-if="role.roleName.length > 8" :title="role.roleName" class="ellipsis">{{ role.roleName.substring(0,
              8)}}...</span>
            <span v-else>{{ role.roleName }}</span>
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item prop="status" :label="$t('user.status')">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">{{ $t("user.status0") }}</el-radio>
          <el-radio :label="1">{{ $t("user.status1") }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { isEmail, isMobile } from "@/utils/utils";
import { IObject } from "@/types/interface";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const roleList = ref<any[]>([]);
const taskleader = ref([] as any[]);
const postList = ref<any[]>([]);
const dataFormRef = ref();


const dataForm = reactive({
  skillGroupId: "",
  userId: null,
  username: "",
  deptId: "",
  deptName: "",
  password: "",
  confirmPassword: "",
  realName: "",
  gender: 0,
  email: "",
  mobile: "",
  roleIdList: [] as IObject[],
  postIdList: [] as IObject[],
  status: 1,
  skillGroupList: [] as number[],
  type: "",
  seatUser: null as any,
  remark: "",
});

const validatePassword = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (!dataForm.userId && !/\S/.test(value)) {
    return callback(new Error(t("validate.required")));
  }
  callback();
};
const validateConfirmPassword = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (!dataForm.userId && !/\S/.test(value)) {
    return callback(new Error(t("validate.required")));
  }
  if (dataForm.password !== value) {
    return callback(new Error(t("user.validate.confirmPassword")));
  }
  callback();
};
const validateEmail = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (value && !isEmail(value)) {
    return callback(new Error(t("validate.format", { attr: t("user.email") })));
  }
  callback(); 1
};
const validateMobile = (rule: any, value: string, callback: (e?: Error) => any): any => {
  if (value && !isMobile(value)) {
    return callback(new Error(t("validate.format", { attr: t("user.mobile") })));
  }
  callback();
};
const rules = ref({
  username: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  deptName: [{ required: true, message: t("validate.required"), trigger: "change" }],
  password: [
    { validator: validatePassword, message: '密码不能为空', trigger: 'change' },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 检查长度
        if (!value) {
          return callback();
        }
        if (value.length < 8) {
          callback(new Error('密码长度不能小于8位'));
        } else {
          // 检查是否包含大小写字母和数字
          let hasUpper = false;
          let hasLower = false;
          let hasNumber = false;
          for (let i = 0; i < value.length; i++) {
            let char = value.charAt(i);
            if (char >= 'A' && char <= 'Z') {
              hasUpper = true;
            } else if (char >= 'a' && char <= 'z') {
              hasLower = true;
            } else if (char >= '0' && char <= '9') {
              hasNumber = true;
            }
          }
          if (!hasUpper) {
            callback(new Error('密码需要包含大写字母'));
          } else if (!hasLower) {
            callback(new Error('密码需要包含小写字母'));
          } else if (!hasNumber) {
            callback(new Error('密码需要包含数字'));
          } else {
            callback();
          }
        }
      },
      trigger: 'change'
    }
  ],
  // password: [{ validator: validatePassword, trigger: "blur" }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: "blur" }],
  realName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  seatUser: [{ validator: validateEmail, trigger: "blur" }],
  mobile: [{ validator: validateMobile, trigger: "blur" }],
});

const init = (userId?: number) => {
  visible.value = true;
  dataForm.userId = null;
  dataForm.deptId = "";
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getRoleList()]).then(() => {
    if (userId) {
      getInfo(userId);
    }
  });
};

// 获取角色列表
const getRoleList = () => {
  return baseService.get("/sys/role/list1").then((res) => {
    roleList.value = res.data;
  });
};

// 获取信息
const getInfo = (userId: number) => {
  baseService.get(`/sys/user/${userId}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};


// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.userId ? baseService.post : baseService.put)("/sys/user", {
      ...dataForm,
      roleIdList: [...dataForm.roleIdList],
      type: dataForm.type ? Number(dataForm.type) : null,
    }).then(() => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
          dataForm.type = ""
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>

<style lang="less" scoped>
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}

.el-form-item::v-deep {
  .el-checkbox-group {
    .el-checkbox {
      width: 120px;
    }
  }
}
</style>
